<template>
  <el-drawer class="drawer-container" :title="title" :visible.sync="visible" append-to-body destroy-on-close
             :wrapper-closable="false" size="880px">
    <el-form ref="form" :model="formdata" :rules="formrule" label-position="right" label-suffix=":" label-width="100px">
      <el-row>
        <el-col :span="24">
          <el-form-item label="上级菜单" prop="pid">
            <a-tree-select v-model="formdata.pid" placeholder="选择上级菜单" :tree-data="localDict.tree_data"
                           :dropdown-style="{'z-index': '3000 !important', maxHeight: '300px', overflow: 'auto' }"
                           :replace-fields="{children:'children', label:'label', key:'id', value: 'id'}"
                           allow-clear style="width: 100%;"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="菜单名称" prop="name">
            <el-input v-model="formdata.name" placeholder="请输入菜单名称"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="菜单编码" prop="code">
            <el-input v-model="formdata.code" placeholder="请输入菜单名称"/>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="菜单图标" prop="icon">
            <el-popover placement="bottom-start" trigger="click" width="460" @show="$refs['iconSelect'].reset()">
              <icon-select ref="iconSelect" :active-icon="formdata.icon" @selected="handleSelectIcon"/>
              <template v-slot:reference>
                <el-input v-model="formdata.icon" placeholder="点击选择图标" readonly>
                  <template v-slot:prefix>
                    <svg-icon v-if="formdata.icon" :icon-class="formdata.icon" style="width: 25px;"/>
                    <i v-else class="el-icon-search el-input__icon"/>
                  </template>
                </el-input>
              </template>
            </el-popover>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="菜单类型" prop="type">
            <el-radio-group v-model="formdata.type">
              <el-radio v-for="(item,index) in localDict.menu_type" :key="index" :label="item.value">
                {{ item.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="status" label="菜单状态">
            <el-radio-group v-model="formdata.status">
              <el-radio v-for="(item,index) in localDict.system_status" :key="index" :label="item.value">
                {{ item.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col v-if="formdata.type !== 'F'" :span="12">
          <el-form-item prop="url">
              <span slot="label">
                <el-tooltip content="访问的路由地址，如：`user`，如外网地址需内链访问则以`http(s)://`开头" placement="top">
                <i class="el-icon-question"></i>
                </el-tooltip>
                路由地址
              </span>
            <el-input v-model="formdata.url" placeholder="请输入路由地址"/>
          </el-form-item>
        </el-col>
        <el-col v-if="formdata.type === 'C'" :span="12">
          <el-form-item prop="queryParam">
            <el-input v-model="formdata.queryParam" maxlength="255" placeholder="请输入路由参数"/>
            <span slot="label">
                <el-tooltip content='访问路由的默认传递参数，如：`{"id": 1, "name": "ry"}`' placement="top">
                <i class="el-icon-question"></i>
                </el-tooltip>
                路由参数
              </span>
          </el-form-item>
        </el-col>
        <el-col v-if="formdata.type === 'C'" :span="12">
          <el-form-item prop="component" label="组件名称">
            <el-input v-model="formdata.component" placeholder="请输入组件路径"/>
          </el-form-item>
        </el-col>
        <el-col v-if="formdata.type === 'C'" :span="12">
          <el-form-item prop="path" label="组件路径">
            <el-input v-model="formdata.path" maxlength="100" placeholder="请输入权限标识"/>
          </el-form-item>
        </el-col>
        <el-col v-if="formdata.type !== 'F'" :span="12">
          <el-form-item prop="isFrame">
              <span slot="label">
                <el-tooltip content="选择是外链则路由地址需要以`http(s)://`开头" placement="top">
                <i class="el-icon-question"></i>
                </el-tooltip>
                是否外链
              </span>
            <el-switch v-model="formdata.frame" active-text="是" inactive-text="否"/>
          </el-form-item>
        </el-col>
        <el-col v-if="formdata.type !== 'F'" :span="12">
          <el-form-item prop="visible">
              <span slot="label">
                <el-tooltip content="选择隐藏则路由将不会出现在侧边栏，但仍然可以访问" placement="top">
                <i class="el-icon-question"></i>
                </el-tooltip>
                显示状态
              </span>
            <el-switch v-model="formdata.visible" active-text="显示" inactive-text="隐藏"/>
          </el-form-item>
        </el-col>
        <el-col v-if="formdata.type === 'C'" :span="12">
          <el-form-item prop="isCache">
              <span slot="label">
                <el-tooltip content="选择是则会被`keep-alive`缓存，需要匹配组件的`name`和地址保持一致" placement="top">
                <i class="el-icon-question"></i>
                </el-tooltip>
                是否缓存
              </span>
            <el-switch v-model="formdata.cache" active-text="缓存" inactive-text="不缓存"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="显示排序" prop="sort">
            <el-input-number v-model="formdata.sort" :min="0" controls-position="right"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="菜单描述">
        <el-input v-model="formdata.remark" :rows="3" placeholder="请输入菜单描述" type="textarea"/>
      </el-form-item>
    </el-form>
    <div class="drawer-footer">
      <el-button size="mini" :loading="loading" type="primary" @click="handleSubmit">确定</el-button>
      <el-button size="mini" @click="handleCancel">取消</el-button>
    </div>
  </el-drawer>
</template>

<script>

import IconSelect from "@/components/IconSelect/index.vue";
import {getOne, save} from "@/api/base";
import {treeselect} from "@/api/tree";

export default {
  name: "MenuModel",
  components: {IconSelect},
  data() {
    return {
      title: '',
      visible: false,
      loading: false,
      baseUrl: '/system/menu',
      formdata: {},
      formrule: {
        code: [
          {required: true, message: '菜单编码不能为空', trigger: 'blur'},
          {pattern: /^\w{2,30}$/, message: '菜单编码只能包含数字、字母、下划线,长度在2-30个字符', trigger: 'blur'},
        ],
        name: [
          {required: true, message: '菜单名称不能为空', trigger: 'blur'},
        ],
        type: [
          {required: true, message: '菜单类型不能为空', trigger: 'blur'},
        ],
        status: [
          {required: true, message: '菜单状态不能为空', trigger: 'blur'},
        ],
        url: [
          {required: true, message: '访问地址不能为空', trigger: 'blur'},
        ],
      },
      localDict: {
        tree_data: [],
        menu_type: [],
        system_status: []
      },
    }
  },
  created() {
    this.getLocalDict();
  },
  methods: {
    add(pid) {
      this.resetForm('form')
      this.formdata = {pid: pid, frame: false, visible: true, cache: true, status: '00'}
      this.visible = true
      this.title = '新增菜单'
    },
    edit(id) {
      this.resetForm('form')
      getOne(this.baseUrl, id).then(res => {
        this.formdata = res.data
        this.visible = true
        this.title = '修改菜单'
      })
    },
    async getLocalDict() {
      await this.getStaticData('system-menu-type').then(res => {
        this.localDict.menu_type = res.data
      })
      await this.getStaticData('system-status').then(res => {
        this.localDict.system_status = res.data
      })
      await treeselect(this.baseUrl).then(res => {
        console.log("result:", res)
        this.localDict.tree_data = []
        const menu = {
          id: "0",
          key: "0",
          title: '主类目',
          value: "0",
          label: '主类目',
          hasChild: true,
          children: res.data.trees
        };
        this.localDict.tree_data.push(menu)
        console.log("localdict:", this.localDict)
      });
    },
    // 选择图标
    handleSelectIcon(name) {
      this.formdata.icon = name;
    },
    handleSubmit() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.loading = true
          save(this.baseUrl, this.formdata).then(() => {
            this.$modal.msgSuccess("保存成功");
            this.visible = false;
            this.resetForm('form')
            this.$emit('ok')
          }).finally(() => {
            this.loading = false
          });
        }
      });
    },
    handleCancel() {
      this.visible = false
      this.submitting = false
      this.resetForm('form')
      this.$emit('close')
    }
  }
}
</script>
